//author:kakake
class tsregisterService {
    public data = {
        dbConn: TSLobsterAPI.Program.GetDbConn(),
        WorkId: 1
    }

    public hisinterface: tshisinterfaceController;
    public dao: tsregisterDao;

    constructor(workid: number) {
        this.data.WorkId = workid;
        this.do_registeredpayment.WorkId = TSLobsterAPI.Program.GetWorkId();
        this.hisinterface = new tshisinterfaceController(1);
        this.dao = new tsregisterDao(this.data.WorkId);
    }

    //挂号记录                                                                                                                                                                  
    public do_registeredpayment = {
        model: {
            "Id": 0,
            "RegType": 1,
            "CardType": "",
            "CardNum": '',
            "MPUserID": "",
            "PatId": "",
            "PatName": "",
            "PatientId": 0,
            "HisEmpId": 0,
            "HisDeptId": 0,
            "DeptId": 0,
            "DeptName": "",
            "EmpId": 0,
            "EmpName": "",
            "Regid": "",
            "RegDate": "",
            "RegRange": "",
            "RegSchedType": 0,
            "Timeid": "",
            "PayMode": 1,//1微信
            "PayAmt": 0,
            "RegState": 0,
            "OrderState": 0,
            "CreateTime": "",
            "UpdateTime": "",
            "DeleteFlag": 0,
            "Sex": 0,
            "Birthday": "",
            "Phone": "",
            "WorkId": 1
        }, //实体模型
        tablename: "WPMT_RegisteredPayment",         //表名
        key: "Id",                  //主键字段
        val: "0",                   //主键值
        objval: {},                 //实体值
        where: "",                  //查询条件
        pageinfo: {},               //分页对象 
        WorkId: 1
    }

    //计算排班
    public countSchedule(allschedulelist: any, doctId: number, regdate?: string) {
        let IsHave = 0;//无号
        let IsFull = 0;
        let AllCount = 0;//总号源数
        let HaveCount = 0;//剩余号源数
        //找出医生索引
        let index = allschedulelist.map(x => { return x.DoctId; }).indexOf(doctId);
        if (regdate) {
            if (index > -1) {
                //找出日期相同的索引
                let i_arr = allschedulelist[index].ItemA.map((x, i) => {
                    if (x.RegDate == regdate) {
                        return i;
                    } else {
                        return -1;
                    }
                });
                //过滤掉无效的索引
                i_arr = i_arr.filter(x => x >= 0);
                if (i_arr.length > 0) {
                    IsHave = 1;//有号
                    //循环索引累加号源
                    i_arr.forEach(i => {
                        AllCount += parseInt(allschedulelist[index].ItemA[i].AllCount);
                        HaveCount += parseInt(allschedulelist[index].ItemA[i].HaveCount);
                    })
                    if (HaveCount == 0) {
                        IsFull = 1;//已约满
                    }
                }
            }
        } else {
            if (index > -1) {
                IsHave = 1;//有号
                //计算总号源
                AllCount = allschedulelist[index].ItemA.map(x => { return x.AllCount; }).reduce((a, b) => { return parseInt(a) + parseInt(b); });
                //计算剩余号源
                HaveCount = allschedulelist[index].ItemA.map(x => { return x.HaveCount; }).reduce((a, b) => { return parseInt(a) + parseInt(b); });
                if (HaveCount == 0) {
                    IsFull = 1;//已约满
                }
            }
        }
        return { IsHave: IsHave, IsFull: IsFull, HaveCount: HaveCount, AllCount: AllCount };
    }

    /**
     * 预约挂号
     * 1、生成挂号记录，状态为待付款
     * 2、调用支付系统，付款
     * 3、调用his系统接口，挂号
     * 4、更新挂号记录，状态为已付款
     */
    public register(model) {
        // var model = JSON.parse(TSLobsterAPI.Program.RequestBody());
        model.CreateTime = TSLobsterAPI.Utils.getCurrTime("yyyy-MM-dd HH:mm:ss");
        model.UpdateTime = TSLobsterAPI.Utils.getCurrTime("yyyy-MM-dd HH:mm:ss");
        model.HisEmpId = model.EmpId;
        model.HisDeptId = model.DeptId;

        model.RegState = 1;//预约中
        model.PayMode = 1;//微信
        model.OrderState = 1;//订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        model.WorkId = TSLobsterAPI.Program.GetWorkId();
        this.do_registeredpayment.objval = model;
        TSLobsterAPI.DbHelper.SaveModel(this.data.dbConn, this.do_registeredpayment);
        model.Id = this.do_registeredpayment.objval['Id'];

        let workid = TSLobsterAPI.Program.GetWorkId();
        let appid = TSLobsterAPI.Program.GetAppId();
        let ret = TSLobsterAPI.AppFunction.GetSystemConfigs(workid, appid, 'SubMchId');
        // TSLobsterAPI.Utils.TrackLog('SubMchId',ret);
        if (!ret.data.config.SubMchId) {
            throw '系统参数SubMchId没有配置';
        }

        //获取收银台页面
        let param = {
            SubMchId: ret.data.config.SubMchId,
            BusinessOrderNo: model.Id.toString(),
            OrderType: 1,//业务类型 1预约挂号 2自助缴费
            PayType: 1,//默认1 微信支付
            PayScene: 1,//1 h5 2小程序 3app
            Price: model.PayAmt * 100, //单位分
            Body: '预约挂号',//商品描述
            Memo: '备注'//可以不填
        };
        // TSLobsterAPI.Utils.TrackLog('param',param);
        let res = TSLobsterAPI.AppFunction.CallOutService(appid, 'pay.pay.preorder', param);
        TSLobsterAPI.Utils.TrackLog('payredirecturl', res);
        let url = res.data.payredirecturl;//收银台界面，支付成功后回调订阅服务register.register.toregister，然后会调用his接口

        //测试支付成功后调用his接口
        // this.registerpaysuccess({ BusinessOrderNo: model.Id });

        return { result: true, url: url };
    }

    /**
     * 取消预约
     * 1、更新挂号记录中状态为退款中
     * 2、调用his接口，取消挂号记录
     * 3、调用支付系统，退款
     * 4、更新挂号记录中状态为退款完成
     */
    public cancelregister(id) {
        // var id = TSLobsterAPI.Program.RequestQuery('id');
        var info = this.dao.getRegisteredInfo(parseInt(id));
        if (info) {
            if (info.GetNumberState == 1) {
                throw "已取号，无法取消";
            } if (info.RegState > 2) {
                throw "无法取消";
            } if (info.RegState == 1 || info.RegState == 2) {
                this.dao.cancelregister(parseInt(id));
                this.hisinterface.cancelregister({ Regno: info.RegNo, RegDate: info.RegDate });

                //调用支付系统退款接口
                //this.cancelregisterrefundsuccess({BusinessOrderNo:id});
                let workid = TSLobsterAPI.Program.GetWorkId();
                let appid = TSLobsterAPI.Program.GetAppId();
                let ret = TSLobsterAPI.AppFunction.GetSystemConfigs(workid, appid, 'SubMchId');
                // TSLobsterAPI.Utils.TrackLog('SubMchId',ret);
                if (!ret.data.config.SubMchId) {
                    throw '系统参数SubMchId没有配置';
                }
                let param = {
                    SubMchId: ret.data.config.SubMchId,
                    BusinessOrderNo: id.toString(),
                    BusinessRefundNo: info.RegNo,
                    PayType: 1,//默认1 微信支付
                    RefundRealFee: parseFloat(info.PayAmt) * 100, //单位分
                    RefundDesc: '预约挂号退款',//商品描述 
                };
                // TSLobsterAPI.Utils.TrackLog('param',param);
                let res = TSLobsterAPI.AppFunction.CallOutService(appid, 'pay.pay.refund', param);
                TSLobsterAPI.Utils.TrackLog('pay.pay.refund', res);
            }
        } else {
            throw '记录不存在';
        }

        return { result: true };
    }

    /**
     * 支付回调成功
     */
    public registerpaysuccess(backpayobj: Backpayobject) {

        //let TranSerNo = '';
        //let OrderNo = '';
        let PayMode = 1;//1微信

        let reginfo = this.dao.getRegisteredInfo(parseInt(backpayobj.BusinessOrderNo));

        let param2 = {
            DeptId: reginfo.DeptId,
            DoctId: reginfo.EmpId,
            Regid: reginfo.Regid,
            RegDate: reginfo.RegDate,
            Timeid: reginfo.Timeid,
            CardType: reginfo.CardType,
            CardNum: reginfo.CardNum,
            TranSerNo: backpayobj.TransactionId,
            PayTime: TSLobsterAPI.Utils.getCurrTime(null),
            PayMode: PayMode,
            TotalRegFee: reginfo.PayAmt
        }
        let ret2 = this.hisinterface.register(param2);
        if (ret2.result) {
            let regno = ret2.Regno;//挂号id
            let location = ret2.Location;//科室地址

            this.dao.updateRegPayed(parseInt(backpayobj.BusinessOrderNo), regno, location, backpayobj.TransactionId, backpayobj.OrderNo, PayMode);
        } else {
            throw '调用his接口失败';
        }
        return { result: true };
    }

    /**
     * 退款成功回调
     * 更新挂号记录中状态为退款完成
     */
    public cancelregisterrefundsuccess(backrefundobj: Backrefundobject) {
        this.dao.cancelregisterfinshed(parseInt(backrefundobj.BusinessOrderNo),backrefundobj.RefundNo,backrefundobj.RefundTransactionId);
        return { result: true };
    }
}